package com.snailcatmall.www.serversocket.netty.heartbeatTools;


import com.snailcatmall.www.serversocket.netty.threadTools.NettyClientTimestampVerification;
import com.snailcatmall.www.serversocket.pojo.ClientInfo;
import com.snailcatmall.www.serversocket.tools.GlobalStaticClass;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.net.SocketAddress;
import java.util.Calendar;
import java.util.Map;

/**
 * @see NettyFromClientHeartbeatDetection  初始化管道每次收到消息的时候更新集合中的时间戳
 */
public class NettyFromClientHeartbeatDetection extends ChannelHandlerAdapter {


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        refreshMessages(ctx);
    }

    private void refreshMessages(ChannelHandlerContext ctx) {
        for (Map.Entry<SocketAddress, ClientInfo> entrySet: GlobalStaticClass.channelHandlerContextMap.entrySet()){
            if(entrySet.getKey().equals(ctx.channel().localAddress())){
                ClientInfo clientInfo = new ClientInfo();
                clientInfo.setTimeStamp(Calendar.getInstance().getTimeInMillis());
                clientInfo.setIsDbClient(entrySet.getValue().getIsDbClient());
                clientInfo.setChannelHandlerContext(entrySet.getValue().getChannelHandlerContext());
                clientInfo.setGroup(entrySet.getValue().getGroup());
                GlobalStaticClass.channelHandlerContextMap.put(entrySet.getKey(),clientInfo);
                System.out.println("刷新时间戳: " +clientInfo.toString());
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        GlobalStaticClass.threadPoolExecutor.submit(new NettyClientTimestampVerification());
    }
}
